package com.mall.biz.user.record;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mall.client.mall.MallService;
import com.mall.client.mallGroupBuy.MallGroupbBuyService;
import com.mall.client.trade.TradeService;
import com.mall.pojo.Trade;
import com.mall.pojo.TradeExample;
import com.mall.pojo.TradeExample.Criteria;
import com.mall.query.TradeRecordQuery;
import com.mall.vo.trade.TradeVO;

@Service
public class RecordBizImpl {

	@Autowired
	private TradeService tradeService;
	@Autowired
	private MallService mallService;
	@Autowired
	private MallGroupbBuyService mallGroupBuyService;
	

	/**
	 * 团购
	 * @param tradeRecordQuery
	 * @return
	 */
	public List<TradeVO> getTradeRecordByQuery(TradeRecordQuery tradeRecordQuery) {
		List<Trade> tradeList = getTradeListByQuery(tradeRecordQuery);
		List<TradeVO> tradeVOList = new ArrayList<>();
		TradeVO tradeVO = null;
		Trade trade = null;
		for (int i = 0; i < tradeList.size(); i++) {
			tradeVO = new TradeVO();
			trade = tradeList.get(i);
			Long orPrice = null;
			if(trade.getDiscountPrice()!=null && trade.getDiscountPrice()>0){
				orPrice = trade.getPrice()+trade.getDiscountPrice();
			}else{
				orPrice = trade.getPrice();
			}
			tradeVO.setMall(this.mallService.getMallById(trade.getMallId()));
			tradeVO.setMallGroupBuy(this.mallGroupBuyService.getMallGroupBuyById(trade.getParentId()));
			tradeVO.setTrade(trade);
			tradeVO.setOrPrice(orPrice);
			tradeVOList.add(tradeVO);
			if(trade.getDiscountPrice() != null){
				tradeVO.setOrPrice(trade.getPrice()+trade.getDiscountPrice());
			}
		}
		return tradeVOList;
	}

	/**
	 * 共用list
	 * @param tradeRecordQuery
	 * @return
	 */
	private List<Trade> getTradeListByQuery(TradeRecordQuery tradeRecordQuery) {
		
		if (tradeRecordQuery.getUserId() == null || tradeRecordQuery.getUserId() <= 0) {
			return null;
		}
		TradeExample example = new TradeExample();
		example.setOrderByClause("id desc");
		example.setStart(tradeRecordQuery.getPage().getBegin());
		example.setLimit(tradeRecordQuery.getPage().getLength());
		Criteria criteria = example.createCriteria();
		criteria.andBuyUserIdEqualTo(tradeRecordQuery.getUserId());// 当前用户的
		if (tradeRecordQuery.getStatus() != null) {
			criteria.andStatusEqualTo(tradeRecordQuery.getStatus());
		}else{
			ArrayList<Integer> a = new ArrayList<Integer>();
			if(tradeRecordQuery.getType()!=9){
				a.add(-1);	
			}
			a.add(-2);
			a.add(-8);
			criteria.andStatusNotIn(a);
			
		}
		if (tradeRecordQuery.getType() != null && tradeRecordQuery.getType() > 0) {
			criteria.andTypeEqualTo(tradeRecordQuery.getType());
		}
		List<Trade> tradeList = this.tradeService.getTradeMessListByExample(example);
		return tradeList;
	}

}
